var dbConfig = require('../../util/dbconfig');
var vertoken = require('../../util/token_vertify.js');
//查询主列表(ok)
getMeauList = async (req, res) => {
	var sql = 'select * from meauLists';
	var sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,getMeauList",
				"code": 500
			});
		} else {
			var list = [];
			var listChildren = await getMeauListChildren();
			var fathernumber = JSON.parse((JSON.stringify(data))).length;
			for (var i = 1; i <= fathernumber; i++) {
				list.push([]); //菜单插入[]以便子元素插入
			}
			//管理员菜单渲染
			for (var i of JSON.parse(listChildren)) {
				for (var j = 1; j <= fathernumber; j++) {
					list[j - 1].push(check(i, j));
				}
			}
			function check(i, number) {
				if (i.pid == number) {
					return i
				} else {
					return 0;
				}
			};
			//过滤掉list为 0的值进行处理
			var newdata = [];
			for (var x of list) {
				x = x.filter(item => item);
				newdata.push(x)
			}
			for (var i in data) {
				data[i].children = newdata[i] 
			}
			res.send({
				"data": data,
				"code": 200,
				"text": "菜单获取成功"
			})
		}
	}

	dbConfig.sqlConnection(sql, sqlArr, cb)
}

//查询附属列表
async function getMeauListChildren() {
	var sql = "select * from meauLists_children";
	var sqlArr = [];
	let data = await dbConfig.SySqlConnect(sql, sqlArr);
	return JSON.stringify(data);
}

module.exports = {
	getMeauList
}
